import {registerDecorator, ValidationOptions, ValidationArguments} from 'class-validator';

// todo 去封装类型判断工具
function validator(list: unknown) {
    try {
        const isArray = Array.isArray(list);

        if (!isArray) {
            return false;
        }

        const validationSpecifications = list.every((value: any) => {
            return typeof value.specification === "string" &&
                typeof value.price === "number" &&
                typeof value.amount === "number" &&
                typeof value.currency === "string"
        });
        return validationSpecifications;
    } catch (e: any) {
        return false;
    }
}

export function ShopSupplierSpecificationValidator(validationOptions?: ValidationOptions) {
    return function (object: Record<string, any>, propertyName: string) {
        registerDecorator({
            name: 'SupplierSpecificationValidator',
            target: object.constructor,
            propertyName: propertyName,
            constraints: [],
            options: {message: "规格格式错误", ...validationOptions},
            validator: {
                validate(value: any, args: ValidationArguments) {
                    return validator(value);
                },
            },
        });
    };
}